<template>
  <div class="content">
    <a-table
        :columns="userColumns"
        :data-source="userData"
        :pagination="{ pageSize: 10, current: currentPage, total: totalUsers }"
        @change="handleTableChange"
        bordered
    >
      <template #headerCell="{ column }">
        <template v-if="column.key === 'userName' || column.key === 'userProfile'">
          <div class="table-header">
            <span>{{ column.title }}</span>
            <a-dropdown :trigger="['click']" v-if="!searchState[column.key + 'Visible']">
              <a class="ant-dropdown-link" @click.prevent="toggleSearch(column.key)">
                <search-outlined />
              </a>
            </a-dropdown>
            <a-input
                v-if="searchState[column.key + 'Visible']"
                v-model:value="searchForm[column.key]"
                :placeholder="'搜索' + column.title"
                style="width: 120px; margin-left: 8px"
                @change="debouncedSearch"
                @blur="searchState[column.key + 'Visible'] = false"
                allowClear
            />
          </div>
        </template>
        <template v-else-if="column.key === 'userRole'">
          <div class="table-header">
            <span>{{ column.title }}</span>
            <a-dropdown :trigger="['click']">
              <a class="ant-dropdown-link" @click.prevent>
                <filter-outlined />
              </a>
              <template #overlay>
                <a-menu>
                  <a-menu-item @click="handleRoleFilter('')">全部</a-menu-item>
                  <a-menu-item @click="handleRoleFilter('user')">普通用户</a-menu-item>
                  <a-menu-item @click="handleRoleFilter('admin')">管理员</a-menu-item>
                  <a-menu-item @click="handleRoleFilter('ban')">封禁用户</a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </div>
        </template>
        <template v-else>
          {{ column.title }}
        </template>
      </template>
      
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.editable">
          <div v-if="editingKey === record.id">
            <a-input
                v-if="column.dataIndex === 'userName'"
                v-model:value="editForm.userName"
                style="margin: -5px 0"
            />
            <a-input
                v-else-if="column.dataIndex === 'userProfile'"
                v-model:value="editForm.userProfile"
                style="margin: -5px 0"
            />
            <a-select
                v-else-if="column.dataIndex === 'userRole'"
                v-model:value="editForm.userRole"
                style="width: 100%"
            >
              <a-select-option value="user">普通用户</a-select-option>
              <a-select-option value="admin">管理员</a-select-option>
              <a-select-option value="ban">封禁用户</a-select-option>
            </a-select>
          </div>
          <div v-else>
            {{ record[column.dataIndex] }}
          </div>
        </template>
        <template v-else-if="column.key === 'action'">
          <div v-if="editingKey === record.id">
            <a-button type="link" @click="saveEdit(record.id)">保存</a-button>
            <a-button type="link" @click="cancelEdit">取消</a-button>
          </div>
          <div v-else>
            <a-button type="link" @click="edit(record)">编辑</a-button>
          </div>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { UserControllerService } from '../openapi/api';
import { FilterOutlined, SearchOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';

// 添加防抖函数
const debounce = (fn, delay = 500) => {
  let timer = null;
  return function(...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

// 添加以下定义
const userData = ref([]);
const currentPage = ref(1);
const totalUsers = ref(0);

const searchForm = ref({
  userName: '',
  userProfile: '',
  userRole: ''
});

const searchState = ref({
  userNameVisible: false,
  userProfileVisible: false
});

const toggleSearch = (key) => {
  searchState.value[key + 'Visible'] = true;
};

const editForm = ref({});
const editingKey = ref('');

const edit = (record) => {
  editingKey.value = record.id;
  editForm.value = { ...record };
};

const saveEdit = async (id) => {
  try {
    await UserControllerService.updateUserUsingPost({
      userUpdateRequest: {
        id: id,
        userName: editForm.value.userName,
        userProfile: editForm.value.userProfile,
        userRole: editForm.value.userRole
      }
    });
    editingKey.value = '';
    message.success('修改成功');
    handleSearch();
  } catch (error) {
    message.error('修改失败');
  }
};

const cancelEdit = () => {
  editingKey.value = '';
};

const userColumns = [
  { 
    title: '用户ID', 
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  { 
    title: '用户昵称', 
    dataIndex: 'userName',
    key: 'userName',
    editable: true
  },
  { 
    title: '用户简介', 
    dataIndex: 'userProfile',
    key: 'userProfile',
    editable: true
  },
  { 
    title: '用户角色', 
    dataIndex: 'userRole',
    key: 'userRole',
    editable: true
  },
  { 
    title: '操作', 
    key: 'action',
    width: 120
  }
];

const handleSearch = async () => {
  try {
    const params = {
      ...searchState.value,
      current: currentPage.value,
      pageSize: 10
    };
    const response = await UserControllerService.listUserByPageUsingPost({ userQueryRequest: params });
    userData.value = response.data.records;
    totalUsers.value = response.data.total;
  } catch (error) {
    message.error('搜索失败');
  }
};

// 创建带防抖的搜索函数
const debouncedSearch = debounce(handleSearch);


// 其他搜索方法保持原样
const handleRoleFilter = (role) => {
  searchState.value.userRole = role;
  handleSearch();  // 直接调用，不加防抖
};

const handleTableChange = (pagination) => {
  currentPage.value = pagination.current;
  handleSearch();  // 直接调用，不加防抖
};

onMounted(() => {
  handleSearch();
});
</script>

<style scoped>
.table-header {
  display: flex;
  align-items: center;
}

.ant-dropdown-link {
  margin-left: 8px;
  color: rgba(0, 0, 0, 0.45);
  cursor: pointer;
}

.ant-dropdown-link:hover {
  color: #1890ff;
}
</style>